import { createStore } from "vuex";
import { login, getinfo, logout } from "@/api/manager";
import { setToken, removeToken } from "@/composables/auth";

const store = createStore({
  state() {
    return {
      // 用户信息
      user: {},
      // 侧边栏宽度
      asideWidth: "64px",
      // 菜单列表
      menus: [],
      // 菜单权限
      ruleNames: [],
    };
  },
  mutations: {
    // 记录用户信息
    SET_USERINFO(state, user) {
      state.user = user;
    },
    SET_ASIDEWIDTH(state) {
      state.asideWidth = state.asideWidth == "250px" ? "64px" : "250px";
    },
    SET_MENUS(state, menus) {
      state.menus = menus;
    },
    SET_RULENAMES(state, ruleNames) {
      state.ruleNames = ruleNames;
    },
  },
  actions: {
    // 登录方法
    USER_LOGIN({}, { username, password }) {
      return new Promise((resolve, reject) => {
        login(username, password)
          .then((res) => {
            // 存储token
            setToken(res.token);
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    // 设置用户信息
    GET_INFO({ commit }) {
      return new Promise((resolve, reject) => {
        getinfo()
          .then((res) => {
            commit("SET_USERINFO", res);
            commit("SET_MENUS", res.menus);
            commit("SET_RULENAMES", res.ruleNames);
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    // 退出登录
    USER_LOGOUT({ commit }) {
      // 移除cookie里的token
      removeToken();
      // 清除当前用户状态vuex
      commit("SET_USERINFO", {});
    },
  },
  modules: {},
});

export default store;
